import React, { useState, useEffect } from 'react';
import { useAuth } from '../../contexts/AuthContext';
import { notification } from '../Notification';
import { GalleryModal } from '../index';
interface GenerationCardProps {
  activeType: "image" | "video" | "migration" | "digital" | "action";
  setActiveType: (type: "image" | "video" | "migration" | "digital" | "action") => void;
  selectedFeature: string;
  setSelectedFeature: (feature: string) => void;
  selectedBusiness: string;
  setSelectedBusiness: (business: string) => void;
  onGenerate: (params?: { noiseLevel?: string; atmosphere?: string; referenceFile?: File; referenceImageUrl?: string; prompt?: string }) => Promise<void>;
  onOpenLLM?: () => void;
  onImageUpload?: (imageUrl: string | null, file?: File) => void;
  onReferenceImageUpload?: (imageUrl: string | null) => void; // 参考图上传回调
  uploadedImage?: string | null;
  referenceImage?: string | null; // 参考图URL
  position?: "center" | "bottom";
  width?: string;
  onClearImages?: () => void; // 添加清空图片的回调
  // 智能提示词回调
  onSmartPromptUpdate?: (smartPrompts: { stylePrompt: string; colorPrompt: string; contentPrompt: string }) => void;
  // 编辑模式相关属性
  editMode?: boolean; // 是否为编辑模式
  editImageUrls?: string[]; // 编辑时的图片URL数组
}
import { useFileUpload } from './hooks/useFileUpload';
import { useAnimation } from './hooks/useAnimation';
import ImageUpload from './ImageUpload';
import InputSection from './InputSection';
import Toolbar from './Toolbar';
import '../GenerationCard.css';

const GenerationCard: React.FC<GenerationCardProps> = ({
  activeType,
  setActiveType,
  selectedFeature,
  setSelectedFeature,
  selectedBusiness,
  setSelectedBusiness,
  onGenerate,
  onOpenLLM,
  onImageUpload,
  onReferenceImageUpload,
  uploadedImage,
  referenceImage,
  position = "center",
  width = "100%",
  onClearImages,
  onSmartPromptUpdate,
  editMode = false,
  editImageUrls = [],
}) => {
  const [prompt, setPrompt] = useState("");
  const [stylePrompt, setStylePrompt] = useState("");
  const [colorPrompt, setColorPrompt] = useState("");
  const [contentPrompt, setContentPrompt] = useState("");
  const [noiseLevel, setNoiseLevel] = useState("0.2");
  const [selectedAtmosphere, setSelectedAtmosphere] = useState('阴天氛围');
  const [isMobile, setIsMobile] = useState(false);
  const [isGenerating, setIsGenerating] = useState(false);
  const [isGalleryModalOpen, setIsGalleryModalOpen] = useState(false);
  const [editingImageUrl, setEditingImageUrl] = useState<string | null>(null);
  const [isReferenceModalOpen, setIsReferenceModalOpen] = useState(false);
  const [editingReferenceUrl, setEditingReferenceUrl] = useState<string | null>(null);
  
  const { isAuthenticated, setShowLoginModal } = useAuth();
  
  const {
    referenceFile,
    imagePreview,
    referenceImagePreview,
    fileInputRef,
    referenceFileInputRef,
    handleFileUpload,
    handleReferenceFileUpload,
    triggerFileUpload,
    triggerReferenceFileUpload,
    clearImage,
    clearReferenceImage,
    setImageUrl,
    setReferenceImageUrl
  } = useFileUpload(onImageUpload, onReferenceImageUpload);

  const {
    cardRef,
    uploadRef,
    upload2Ref,
    handleSendClick
  } = useAnimation();

  // 使用传入的 uploadedImage 或内部的 imagePreview
  // 如果 uploadedImage 为 null，则使用 imagePreview；如果 uploadedImage 为 undefined，则使用 imagePreview
  const currentImagePreview = uploadedImage !== undefined ? uploadedImage : imagePreview;

  // 检测移动端
  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth <= 768);
    };
    
    checkMobile();
    window.addEventListener('resize', checkMobile);
    
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  // 设置参考图（如果从外部传入）
  useEffect(() => {
    console.log('GenerationCard 接收到的参考图:', referenceImage);
    if (referenceImage) {
      console.log('设置参考图到内部状态:', referenceImage);
      setReferenceImageUrl(referenceImage);
    }
  }, [referenceImage]);

  // 监听图片预览状态变化
  useEffect(() => {
    // 图片预览状态变化处理
  }, [currentImagePreview]);

  // 处理编辑模式下的图片设置
  useEffect(() => {
    if (editMode && editImageUrls.length > 0) {
      // 设置第一张图片为原图
      if (editImageUrls[0]) {
        // 直接设置内部状态，避免触发父组件的回调
        setImageUrl(editImageUrls[0]);
      }
      
      // 设置第二张图片为参考图（如果有的话）
      if (editImageUrls[1]) {
        setReferenceImageUrl(editImageUrls[1]);
      }
    }
  }, [editMode, editImageUrls, setImageUrl, setReferenceImageUrl]);

  // 监听智能提示词变化并通知父组件 - 使用防抖避免过度更新
  useEffect(() => {
    if (!onSmartPromptUpdate) return;
    
    const timeoutId = setTimeout(() => {
      onSmartPromptUpdate({
        stylePrompt,
        colorPrompt,
        contentPrompt
      });
    }, 300); // 300ms 防抖延迟
    
    return () => clearTimeout(timeoutId);
  }, [stylePrompt, colorPrompt, contentPrompt, onSmartPromptUpdate]);

  // 验证输入并通知父组件
  const handleGenerate = async () => {
    // 设置loading状态
    setIsGenerating(true);
    
    try {
      // 高清放大模式不需要提示词和业态验证
      if (activeType === "digital") {
        // 通知父组件开始生成，传递噪点参数
        await onGenerate({ noiseLevel });
        return;
      }

    // 图片编辑模式（单图指令编辑、双图编辑、双图指令编辑）需要提示词验证
    if (activeType === "action" && (selectedFeature === "单图指令编辑" || selectedFeature === "双图编辑" || selectedFeature === "双图指令编辑")) {
      if (!prompt.trim()) {
        notification.warning('请输入编辑指令');
        setIsGenerating(false);
        return;
      }
      // 单图指令编辑需要上传原图
      if (selectedFeature === "单图指令编辑" && !currentImagePreview) {
        notification.warning('单图指令编辑需要上传原图');
        setIsGenerating(false);
        return;
      }
      // 双图编辑需要上传两张图片
      if (selectedFeature === "双图编辑") {
        if (!currentImagePreview) {
          notification.warning('双图编辑需要上传原图');
          setIsGenerating(false);
          return;
        }
        if (!referenceImagePreview) {
          notification.warning('双图编辑需要上传参考图');
          setIsGenerating(false);
          return;
        }
      }
      // 双图指令编辑需要上传两张图片
      if (selectedFeature === "双图指令编辑") {
        if (!currentImagePreview) {
          notification.warning('双图指令编辑需要上传原图');
          setIsGenerating(false);
          return;
        }
        if (!referenceImagePreview) {
          notification.warning('双图指令编辑需要上传参考图');
          setIsGenerating(false);
          return;
        }
      }
    }
    // 图片生成 - 风格参考模式、图像迁移模式、双图编辑参考风格、光线氛围模式不需要提示词
    else if ((activeType === "image" && selectedFeature === "风格参考") || 
        activeType === "migration" ||
        (activeType === "action" && selectedFeature === "双图编辑参考风格") ||
        (activeType === "action" && selectedFeature === "光线氛围")) {
      // 风格参考模式需要上传参考图
      if (activeType === "image" && selectedFeature === "风格参考" && !referenceImagePreview) {
        notification.warning('风格参考模式需要上传参考图');
        setIsGenerating(false);
        return;
      }
      // 图像迁移模式需要上传原图
      if (activeType === "migration" && !currentImagePreview) {
        notification.warning('图像迁移模式需要上传原图');
        setIsGenerating(false);
        return;
      }
      // 双图编辑参考风格需要上传两张图片
      if (activeType === "action" && selectedFeature === "双图编辑参考风格") {
        if (!currentImagePreview) {
          notification.warning('双图编辑参考风格需要上传原图');
          setIsGenerating(false);
          return;
        }
        if (!referenceImagePreview) {
          notification.warning('双图编辑参考风格需要上传参考图');
          setIsGenerating(false);
          return;
        }
      }
      // 光线氛围模式需要上传原图并选择氛围
      if (activeType === "action" && selectedFeature === "光线氛围") {
        if (!currentImagePreview) {
          notification.warning('光线氛围模式需要上传原图');
          setIsGenerating(false);
          return;
        }
        if (!selectedAtmosphere) {
          notification.warning('光线氛围模式需要选择氛围');
          setIsGenerating(false);
          return;
        }
      }
    } else {
      // 其他模式需要提示词验证
      if (activeType === "video") {
        // 视频生成模式：验证普通提示词
        if (!prompt.trim()) {
          notification.warning('请输入提示词');
          setIsGenerating(false);
          return;
        }
      } else {
        // 图片生成和其他模式：验证智能提示词
        const hasContent = stylePrompt.trim() || colorPrompt.trim() || contentPrompt.trim();
        
        if (!hasContent) {
          notification.warning('请至少填写一个智能提示词字段');
          setIsGenerating(false);
          return;
        }
      }
    }

    // 检查是否选择了业态（高清放大、图像迁移、视频生成、图片编辑模式除外）
    if ((activeType as string) !== "digital" && activeType !== "migration" && activeType !== "video" && activeType !== "action") {
      if (selectedBusiness === '选择业态' || selectedBusiness === '业态选择' || !selectedBusiness) {
        notification.warning('请选择业态');
        setIsGenerating(false);
        return;
      }
    }

      // 通知父组件开始生成，传递相应参数
      if (activeType === "action" && selectedFeature === "光线氛围") {
        await onGenerate({ 
          atmosphere: selectedAtmosphere,
          referenceFile: referenceFile || undefined,
          referenceImageUrl: referenceImagePreview || undefined
        });
      } else if (activeType === "action" && (selectedFeature === "单图指令编辑" || selectedFeature === "双图编辑" || selectedFeature === "双图指令编辑")) {
        await onGenerate({ 
          prompt: prompt,
          referenceFile: referenceFile || undefined,
          referenceImageUrl: referenceImagePreview || undefined
        });
      } else if (activeType === "image" && selectedFeature === "风格参考") {
        await onGenerate({ 
          referenceFile: referenceFile || undefined,
          referenceImageUrl: referenceImagePreview || undefined
        });
      } else if (activeType === "action" && selectedFeature === "双图编辑参考风格") {
        await onGenerate({ 
          referenceFile: referenceFile || undefined,
          referenceImageUrl: referenceImagePreview || undefined
        });
      } else {
        // 对于其他情况（包括图像迁移），也传递参考图
        await onGenerate({ 
          referenceFile: referenceFile || undefined,
          referenceImageUrl: referenceImagePreview || undefined
        });
      }
      
      // 生成完成后清空图片、提示词和其他状态
      clearImage();
      clearReferenceImage();
      setPrompt(''); // 清空普通提示词
      setStylePrompt(''); // 清空智能提示词
      setColorPrompt('');
      setContentPrompt('');
      setSelectedAtmosphere('阴天氛围'); // 重置氛围选择
      setNoiseLevel('0.2'); // 重置噪点级别
      onClearImages?.();
      
    } catch (error) {
      console.error('生成过程中发生错误:', error);
      // 错误处理已经在父组件中完成，这里不需要额外处理
    } finally {
      // 清除loading状态
      setIsGenerating(false);
    }
  };

  // 发送按钮点击处理
  const handleSendClickWrapper = () => {
    handleSendClick(handleGenerate);
  };

  // 处理图片编辑
  const handleImageEdit = (imageUrl: string) => {
    setEditingImageUrl(imageUrl);
    setIsGalleryModalOpen(true);
  };

  // 处理参考图编辑
  const handleReferenceEdit = (imageUrl: string) => {
    setEditingReferenceUrl(imageUrl);
    setIsReferenceModalOpen(true);
  };

  // 处理画布保存
  const handleCanvasSave = (imageData: string) => {
    // 更新图片预览
    onImageUpload?.(imageData);
    setIsGalleryModalOpen(false);
    setEditingImageUrl(null);
  };

  // 处理参考图画布保存
  const handleReferenceCanvasSave = (imageData: string) => {
    // 更新参考图预览
    setReferenceImageUrl(imageData);
    setIsReferenceModalOpen(false);
    setEditingReferenceUrl(null);
  };

  // 处理画布下载
  const handleCanvasDownload = (imageData: string) => {
    const link = document.createElement('a');
    link.download = `edited-image-${Date.now()}.png`;
    link.href = imageData;
    link.click();
  };

  // 处理参考图画布下载
  const handleReferenceCanvasDownload = (imageData: string) => {
    const link = document.createElement('a');
    link.download = `edited-reference-${Date.now()}.png`;
    link.href = imageData;
    link.click();
  };

  return (
    <div
      className={`generation-section ${
        position === "bottom" ? "bottom-position" : ""
      }`}
    >
      <div className="generation-container" style={{ 
        width: isMobile ? '94vw' : (width === '1400px' ? '1440px' : width),
        maxWidth: isMobile ? '94vw' : 'none'
      }}>
        {/* 卡片整体：头部标签 + 主面板 + 底部工具栏 */}
        <div className={`generator-card ${isMobile ? 'mobile' : ''}`} ref={cardRef}>
          <div className="card-body card-panel">
            <div className="upload-input-container">
              {/* 第一个上传区域 - 原图 */}
              <ImageUpload
                onImageUpload={(imageUrl, file) => {
                  if (imageUrl === null) {
                    // 清空内部状态（clearImage内部会调用onImageUpload）
                    clearImage();
                  } else {
                    onImageUpload?.(imageUrl, file);
                  }
                }}
                uploadedImage={currentImagePreview}
                label="原图"
                uploadRef={uploadRef}
                currentImagePreview={currentImagePreview}
                onUploadClick={triggerFileUpload}
                onEdit={handleImageEdit}
              />
              
              {/* 第二个上传区域 - 参考图 */}
              <ImageUpload
                onImageUpload={(imageUrl) => {
                  if (imageUrl === null) {
                    clearReferenceImage();
                  }
                }}
                uploadedImage={referenceImagePreview}
                label="参考图"
                isReference={true}
                uploadRef={upload2Ref}
                currentImagePreview={referenceImagePreview}
                onUploadClick={triggerReferenceFileUpload}
                onEdit={handleReferenceEdit}
              />
              
              <input
                type="file"
                ref={fileInputRef}
                onChange={handleFileUpload}
                accept=".png,.jpg,.jpeg,image/png,image/jpeg"
                style={{ display: "none" }}
              />
              <input
                type="file"
                ref={referenceFileInputRef}
                onChange={handleReferenceFileUpload}
                accept=".png,.jpg,.jpeg,image/png,image/jpeg"
                style={{ display: "none" }}
              />
              
              <InputSection
                activeType={activeType}
                selectedFeature={selectedFeature}
                prompt={prompt}
                setPrompt={setPrompt}
                stylePrompt={stylePrompt}
                setStylePrompt={setStylePrompt}
                colorPrompt={colorPrompt}
                setColorPrompt={setColorPrompt}
                contentPrompt={contentPrompt}
                setContentPrompt={setContentPrompt}
                noiseLevel={noiseLevel}
                setNoiseLevel={setNoiseLevel}
              />
            </div>
          </div>
          
          <div className="card-toolbar">
            <Toolbar
              activeType={activeType}
              setActiveType={setActiveType}
              selectedFeature={selectedFeature}
              setSelectedFeature={setSelectedFeature}
              selectedBusiness={selectedBusiness}
              setSelectedBusiness={setSelectedBusiness}
              onOpenLLM={onOpenLLM}
              onGenerate={handleSendClickWrapper}
              isAuthenticated={isAuthenticated}
              setShowLoginModal={setShowLoginModal}
              selectedAtmosphere={selectedAtmosphere}
              setSelectedAtmosphere={setSelectedAtmosphere}
              isGenerating={isGenerating}
            />
          </div>
        </div>
      </div>
      
      {/* GalleryModal 弹窗 - 原图编辑 */}
      <GalleryModal
        isOpen={isGalleryModalOpen}
        onClose={() => {
          setIsGalleryModalOpen(false);
          setEditingImageUrl(null);
        }}
        imageToEdit={editingImageUrl || undefined}
        onSave={handleCanvasSave}
        onDownload={handleCanvasDownload}
      />
      
      {/* GalleryModal 弹窗 - 参考图编辑 */}
      <GalleryModal
        isOpen={isReferenceModalOpen}
        onClose={() => {
          setIsReferenceModalOpen(false);
          setEditingReferenceUrl(null);
        }}
        imageToEdit={editingReferenceUrl || undefined}
        onSave={handleReferenceCanvasSave}
        onDownload={handleReferenceCanvasDownload}
      />
    </div>
  );
};

export default GenerationCard;
